﻿package com.shuqi.model.parse.parser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.utils.BookBagUtil;
import com.shuqi.database.dao.impl.BookBagCatalogDao;
import com.shuqi.interfaces.OnAfterLoadPage;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.encoding.IEncoding;
import com.shuqi.model.parse.BookContentParserBase;
import com.shuqi.model.parse.HandlerBase;

public class BookContentLocalAppBagParser extends BookContentParserBase {

    public final static String TAG = "BookContentLocalAppBagParser";

    private BookBagCatalogHandler mCatalogHandler;
    /** 目录 */
    private List<BookContentInfo> mCurrCatalogList;

    /** 目录 map */
    private Map<String, BookBagCatalogInfo> mCatalogMap = new HashMap<String, BookBagCatalogInfo>();

    private int mCurPosition = 0;

    /** 根据进度获取章节名 */
    public BookContentInfo getCurCharpterNameFromProgress(Context context, BookContentInfo params) {

        if (params == null || TextUtils.isEmpty(params.getCurChapterCid())) {
            return null;
        }
        String bookId = params.getBookId();

        // 章节cid
        String cid = String.valueOf(params.getIntCurChapterCid());

        // 先初始化目录
        if (mCurrCatalogList == null || mCurrCatalogList.size() == 0) {
            initCatalogList(bookId);
        }

        if (mCurrCatalogList == null || mCurrCatalogList.size() == 0) {
            return null;
        }

        // 根据目录信息获取当前数据
        if (mCatalogMap != null && mCatalogMap.containsKey(cid)) {
            BookBagCatalogInfo catalog = mCatalogMap.get(cid);
            if (catalog == null) {
                return null;
            }
            BookContentInfo info = getBookBagInfo(catalog.getInfo());
            if (info != null) {
                params.setCurChapterName(catalog.getInfo().getCurChapterName());
                return params;
            }
        }

        return params;
    }

    // /** 阅读页调用 */
    @Override
    public BookContentInfo getCurInfos(Context context, BookContentInfo params, boolean isNext,
            OnOneChpaterLoadDone callBack) {
        if (params == null || TextUtils.isEmpty(params.getCurChapterCid())) {
            return null;
        }
        String bookId = params.getBookId();

        // 章节cid
        String cid = String.valueOf(params.getIntCurChapterCid());
        // 先初始化目录
        if (mCurrCatalogList == null || mCurrCatalogList.size() == 0) {
            initCatalogList(bookId);
        }

        if (mCurrCatalogList == null || mCurrCatalogList.size() == 0) {
            return null;
        }

        // 根据目录信息获取当前数据
        if (mCatalogMap != null && mCatalogMap.containsKey(cid)) {
            BookBagCatalogInfo catalog = mCatalogMap.get(cid);
            if (catalog == null) {
                return null;
            }
            BookContentInfo info = getBookBagInfo(catalog.getInfo());
            if (info != null) {
                int positon = catalog.getPosition();
                mCurPosition = positon;
                int catalogSize = mCurrCatalogList.size();
                String preCid = null;
                String nextCid = null;
                if (positon > 0 && positon - 1 < catalogSize) {
                    preCid = mCurrCatalogList.get(positon - 1).getCurChapterCid();
                }
                if (positon + 1 > 0 && positon + 1 < catalogSize) {
                    nextCid = mCurrCatalogList.get(positon + 1).getCurChapterCid();
                }
                params.setCurChapterBytes(info.getChaptercontent().getBytes());
                params.setEncoding(IEncoding.ENCODING_UTF8);
                params.setPreChapterCid(preCid);
                params.setNextChapterCid(nextCid);
                params.setStartIndex(positon);
                params.setTotalLength(catalogSize);
                params.setCurChapterName(catalog.getInfo().getCurChapterName());
                return params;
            }
        }
        return null;
    }

    // 构建目录的map
    private void buildMap() {
        if (mCurrCatalogList != null && mCurrCatalogList.size() > 0) {
            int size = mCurrCatalogList.size();
            for (int i = 0; i < size; i++) {
                BookBagCatalogInfo catalog = new BookBagCatalogInfo();
                catalog.setInfo(mCurrCatalogList.get(i));
                catalog.setPosition(i);
                mCatalogMap.put(mCurrCatalogList.get(i).getCurChapterCid(), catalog);
            }
        }
    }

    private void initCatalogList(String bookId) {
        // 先初始化目录
        List<BookContentInfo> tempList = null;
        tempList = BookBagCatalogDao.getInstance().getBookBagCatalogList(bookId);
        if (tempList == null || tempList.size() == 0) {
            // 检索本地文件,生成目录
            scanBookBagFile(bookId);
        }

        mCurrCatalogList = BookBagCatalogDao.getInstance().getBookBagCatalogList(bookId);

        buildMap();

    }

    private BookContentHandler mBookContentHandler;

    private BookContentInfo getBookBagInfo(BookContentInfo catalog) {
        if (catalog == null || TextUtils.isEmpty(catalog.getFliePath())
                || TextUtils.isEmpty(catalog.getChapterpath())) {
            return null;
        }
        ByteArrayOutputStream as = BookBagUtil.decode2Zip(catalog.getFliePath(), ConfigVersion.SN);
        ByteArrayInputStream is = BookBagUtil.unzip(as, catalog.getChapterpath());
        if (mBookContentHandler == null) {
            mBookContentHandler = new BookContentHandler();
        }
        BookContentInfo info = new BookContentInfo();
        if (is != null) {
            XMLHelper.doInputSteamParse(mBookContentHandler, is);
            info = mBookContentHandler.getParsedData();
        } else {
            info.setChaptercontent("文件已被删除");
        }
        return info;
    }

    @Override
    public BookContentInfo getCurrInfo(Activity context) {
        return null;
    }

    @Override
    public void loadPrevInfo(Activity context, OnAfterLoadPage onAfterLoadPage,
            BookContentInfo params) {

    }

    @Override
    public void loadNextInfo(Activity context, OnAfterLoadPage onAfterLoadPage,
            BookContentInfo params) {

    }

    @Override
    public boolean hasPreChapter(int index) {
        mCurPosition--;
        return mCurPosition > 0;
    }

    @Override
    public boolean hasNextChapter(int index) {
        if (mCurPosition < 0) {
            mCurPosition = 0;
        } else if (mCurPosition >= mCurrCatalogList.size()) {
            mCurPosition = mCurrCatalogList.size() - 1;
        }
        mCurPosition++;
        return mCurPosition < mCurrCatalogList.size();
    }

    @Override
    public List<BookContentInfo> getBookCatalogList() {
        return mCurrCatalogList;

    }

    @Override
    public boolean isPageFetching() {
        return false;
    }


    private void scanBookBagFile(final String bookId) {
        if (TextUtils.isEmpty(bookId)) {
            return;
        }
        if (mCatalogHandler == null) {
            mCatalogHandler = new BookBagCatalogHandler();
        }
        String bookBagPath = Config.BOOKBAG_PATH;

        File file = new File(bookBagPath);
        if (file != null && file.isDirectory()) {
            File[] files = file.listFiles(new FileFilter() {

                @Override
                public boolean accept(File file) {
                    String pattern = "^" + bookId + "_[0-9_]+[0-9]+.sqb" + "$";
                    if (file.isFile() && !TextUtils.isEmpty(file.getName())) {
                        return file.getName().matches(pattern);
                    }
                    return false;
                }
            });
            List<BookContentInfo> list = new ArrayList<BookContentInfo>();
            for (File sqbFile : files) {
                String filePath = bookBagPath + "/" + sqbFile.getName();
                ByteArrayOutputStream as = BookBagUtil.decode2Zip(filePath, ConfigVersion.SN);
                ByteArrayInputStream is = BookBagUtil.unzip(as, "chapterinfo.xml");
                mCatalogHandler.setFilePath(filePath);
                mCatalogHandler.setBookId(bookId);
                XMLHelper.doInputSteamParse(mCatalogHandler, is);
                if (mCatalogHandler.getParsedData() != null) {
                    list.addAll(mCatalogHandler.getParsedData());
                }
            }
            BookBagCatalogDao.getInstance().saveBookBagCatalogList(list, bookId);
        }
    }

    /** 书包目录解析 */
    public static class BookBagCatalogHandler extends HandlerBase {
        private List<BookContentInfo> list;
        private String filePath;
        private String bookId;

        public void startDocument() throws SAXException {
            super.startDocument();
            list = new ArrayList<BookContentInfo>();
        }

        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes)
                throws SAXException {
            if (localName.equals("Chapter")) {
                String chapterName = isNull(attributes, "name");
                try {
                    String[] tmp = chapterName.split("\\.");
                    if (tmp != null && tmp.length == 2) {
                        String cid = tmp[0];
                        Integer.parseInt(cid);
                        BookContentInfo info = new BookContentInfo();
                        info.setCurChapterName(isNull(attributes, "title"));
                        info.setChapterpath(chapterName);
                        info.setCurChapterCid(cid);
                        info.setFliePath(filePath);
                        info.setBookId(bookId);
                        list.add(info);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public List<BookContentInfo> getParsedData() {
            return list;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        public void setBookId(String bookId) {
            this.bookId = bookId;
        }
    }


    /** 书包内容解析 */
    public static class BookContentHandler extends HandlerBase {

        public BookContentInfo info;
        private int inWhich;
        private final int CHAPTER_CONTENT = 1;

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            String value = new String(ch, start, length);
            if (inWhich == CHAPTER_CONTENT) {
                String old_info = this.info.getChaptercontent();
                if (old_info == null) {
                    old_info = "";
                }
                this.info.setChaptercontent(old_info + value);
            }
        }

        public void startDocument() throws SAXException {
            super.startDocument();
            info = new BookContentInfo();
        }

        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes)
                throws SAXException {
            if (localName.equals("ChapterContent")) {
                inWhich = CHAPTER_CONTENT;
            } else {
                inWhich = 0;
            }
        }

        @Override
        public BookContentInfo getParsedData() {
            parseContent(info);
            return info;
        }

        private void parseContent(BookContentInfo info) {
            try {
                // 在章节段首确认加上了两个空格
                if (info != null && info.getChaptercontent() != null) {
                    String content = info.getChaptercontent().trim();
                    content = "  " + content;
                    content =
                            content.replaceAll("<br>", "\n").replaceAll("<br/>", "\n")
                                    .replaceAll("<br />", "\n");
                    info.setChaptercontent(content);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class BookBagCatalogInfo {
        private int position;

        public int getPosition() {
            return position;
        }

        public BookContentInfo getInfo() {
            return info;
        }

        public void setPosition(int position) {
            this.position = position;
        }

        public void setInfo(BookContentInfo info) {
            this.info = info;
        }

        private BookContentInfo info;


    }

    @Override
    public int getPostion(String chapterId) {
        if (mCatalogMap != null) {
            final BookBagCatalogInfo bagInfo = mCatalogMap.get(chapterId);
            if (bagInfo != null) {
                return bagInfo.getPosition();
            }
        }
        return super.getPostion(chapterId);
    }

    public String getChapterId(int position) {
        if (mCurrCatalogList != null) {
            if (position < 0) {
                position = 0;
            }
            if (position > mCurrCatalogList.size() - 1) {
                position = mCurrCatalogList.size() - 1;
            }
            final BookContentInfo contentInfo = mCurrCatalogList.get(position);
            if (contentInfo != null) {
                return contentInfo.getCurChapterCid();
            }
        }

        return super.getChapterId(position);
    }
}
